//
//  ResidentComplainController.m
//  homeland
//
//  Created by Alawn on 13-10-30.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "ResidentComplainController.h"
#import "StreetInfoItem.h"
#import "ResidentDataService.h"
#import "ResidentListViewController.h"
#import "LoginViewController.h"
#define INPUT_VIEW_OFFSET 200.0
@interface ResidentComplainController ()
@property (strong,nonatomic) ResidentDataService *residentDataService;
@property (strong, nonatomic) CommitteesByStreetService *streetService;
@property (strong, nonatomic) NSArray *streetArray;
@property (assign, nonatomic) NSInteger currentStreetId;
-(NSString *)getStreetNameById:(NSInteger)streetId;
@end

@implementation ResidentComplainController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //登录判断----暂时关闭登录要求限制
//    NSString *currentUserName = [UserInfoService getUserInfoService].currentLoginUserName;
//    if (!currentUserName)
//    {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请登录后，使用该功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alert show];
//    }
    // Do any additional setup after loading the view from its nib.
    self.title=@"我要信访";
     self.scrollView.contentSize = CGSizeMake(320.0, 600.0);
    //开始读取街道列表
    self.streetService = [[CommitteesByStreetService alloc]init];
    self.streetService.delegate = self;
    [self.streetService loadDataWithKey:nil];
    [self startLoadingView];
    UserInfo *userInfo = [UserInfoService getUserInfoService].userInfo;
    if (userInfo&&userInfo.streetId && userInfo.streetId != (id)[NSNull null]) {
        self.currentStreetId = userInfo.streetId.integerValue;
    }
    self.residentDataService = [ResidentDataService new];
    _residentDataService.delegate = self;
    self.nameField.inputAccessoryView = [self getInputAccessoryView];
    self.titleField.inputAccessoryView = [self getInputAccessoryView];
    self.addressField.inputAccessoryView = [self getInputAccessoryView];
    self.contentTextView.inputAccessoryView = [self getInputAccessoryView];
     self.happenAddressTextView.inputAccessoryView = [self getInputAccessoryView];
    self.happenAddressTextView.delegate = self;
    self.contentTextView.delegate = self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //初始化读入数据
    UserInfo *userInfo = [UserInfoService getUserInfoService].userInfo;
    if (userInfo) {
        self.nameField.placeholder = userInfo.userName;
        self.nameField.enabled=NO;
    } else {
        self.nameField.enabled = YES;
        self.nameField.placeholder = @"请输入姓名";
    }
    [self.streetButton setTitle:[self getStreetNameById:self.currentStreetId] forState:UIControlStateNormal];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Alert Delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc]initWithNibName:@"LoginViewController" bundle:nil];
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma mark - Data Service Delegate
-(void)loadDataFinished
{
    [self stopLoadingView];
    self.streetButton.enabled = YES;
    self.streetArray = self.streetService.dataList;
    UserInfo *userInfo = [UserInfoService getUserInfoService].userInfo;
    if (userInfo&&userInfo.streetId && userInfo.streetId != (id)[NSNull null]) {
        [self.streetButton setTitle:[self getStreetNameById:userInfo.streetId.integerValue] forState:UIControlStateNormal];
    }
     self.navigationItem.rightBarButtonItem = rightNavButton( self, @selector(rightButtonAction:),@"信访记录");
    if (_residentDataService.dealCode && _residentDataService.dealCode != (id)[NSNull null] &&_residentDataService.dealCode.length > 0) {
        [self showAlert:[NSString stringWithFormat:@"您提交的事项(受理编号%@)已转有关单位办理,您可以凭受理编号与姓名查询办理情况",_residentDataService.dealCode]];
    }
}

-(void)loadDataFaild:(NSString *)msg
{
    [self stopLoadingView];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:@"访问失败,请稍后重试." delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    self.streetButton.enabled = NO;
}

-(void)setEnableToLoadMore:(BOOL)enable
{
    //did nothing
}
#pragma mark - User Service Delegate
-(void)loadDataFinished:(id)result
{
    [self stopLoadingView];
}

-(void)loadUserInfoFaild:(NSString *)msg
{
    [self stopLoadingView];
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
#pragma mark - Button Methods
- (IBAction)commitButtonAction:(id)sender
{
    [self.view endEditing:YES];//关闭键盘
    NSString *title = _titleField.text;
    NSString *name = _nameField.text;
    NSString *content = _contentTextView.text;
    NSString *street = self.streetButton.titleLabel.text;
    if (!title || title.length == 0) {
        [self showAlert:@"标题不能为空."];
        [_titleField becomeFirstResponder];
        return;
    }
    if (!name || name.length == 0) {
        [self showAlert:@"姓名不能为空."];
        [_nameField becomeFirstResponder];
        return;
    }
    if (!content || content.length == 0) {
        [self showAlert:@"信件内容不能为空."];
        [_contentTextView becomeFirstResponder];
        return;
    }
    if (!street || street.length == 0 || [street isEqualToString:@"请选择"]) {
        [self showAlert:@"请选择街道."];
        return;
    }
    ResidentDataItem *residentItem=[[ResidentDataItem alloc]init];
    residentItem.title=title;
    residentItem.happenAddress=self.happenAddressTextView.text;
    residentItem.happenStreet=self.streetButton.titleLabel.text;
    residentItem.content=self.contentTextView.text;
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if (userInfo) {
        residentItem.userName=userInfo.currentLoginUserName;
        residentItem.Phone=userInfo.userInfo.mobile;
    } else {
        residentItem.userName = self.nameField.text;
    }
    
    residentItem.address=self.addressField.text;
    //调用服务
    [self startLoadingViewWithText:@"正在提交..."];
    [_residentDataService postComplainWithDataItem:residentItem];
}
-(void)rightButtonAction:(id)sender
{
    ResidentListViewController *listVC = [[ResidentListViewController alloc]initWithNibName:@"ResidentListViewController" bundle:nil];
    listVC.config = _config;
    [self.navigationController pushViewController:listVC animated:YES];
}
-(void)showAlert:(NSString *) msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}
- (IBAction)streetButtonAction:(id)sender
{
    ChooseStreetViewController *chooseVC = [[ChooseStreetViewController alloc]initWithNibName:@"ChooseStreetViewController" bundle:nil];
    chooseVC.delegate = self;
    chooseVC.streetListService = self.streetService;
    chooseVC.usedForPersonalInfo = YES;
    chooseVC.selectedStreetId = self.currentStreetId;
    [self.navigationController pushViewController:chooseVC animated:YES];
}

-(NSString *)getStreetNameById:(NSInteger)streetId
{
    NSString *name = @"请选择";
    for (StreetInfoItem *item in self.streetArray) {
        if (item.item_id.integerValue == streetId) {
            name = item.item_name;
            break;
        }
    }
    return name;
}
#pragma mark - Choose Callback
-(void)choosedStreet:(NSInteger)streetId{
    self.currentStreetId = streetId;
    [self.streetButton setTitle:[self getStreetNameById:streetId] forState:UIControlStateNormal];
}

#pragma mark - Text Field Delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET/2;
    self.view.frame = frame;
    [UIView commitAnimations];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET/2;
    self.view.frame = frame;
    [UIView commitAnimations];
}

#pragma mark - Text View Delegate
//开始输入的时候向上移动整个界面，这个输入框不会被挡住
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y - INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

//输入结束的时候把整个界面向下移动，这个能恢复正常
-(void)textViewDidEndEditing:(UITextView *)textView
{
    [UIView beginAnimations:@"animation" context:nil];
    [UIView setAnimationDuration:0.2f];
    CGRect frame = self.view.frame;
    frame.origin.y = frame.origin.y + INPUT_VIEW_OFFSET;
    self.view.frame = frame;
    [UIView commitAnimations];
}

#pragma mark - User Service Delegate
-(void)loadUserInfoFinished:(id)result
{
    [self stopLoadingView];
}
@end
